package com.slytherin.sns.spider.task.executor;

import com.slytherin.sns.spider.client.downloader.HttpClientDownloader;
import com.slytherin.sns.spider.core.SlytherinScript;
import com.slytherin.sns.spider.core.SlytherinSpider;
import com.slytherin.sns.spider.empty.BuildScriptParam;
import com.slytherin.sns.spider.emun.SourceEnum;
import com.slytherin.sns.spider.groovy.CategoryScript;
import com.slytherin.sns.spider.mapper.ScriptMapper;
import com.slytherin.sns.spider.mapper.TaskMapper;
import com.slytherin.sns.spider.mapper.empty.ScriptDO;
import com.slytherin.sns.spider.mapper.empty.TaskBO;
import com.slytherin.sns.spider.result.Request;
import com.slytherin.sns.spider.task.SlytherinTaskFactory;
import groovy.lang.GroovyClassLoader;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Site;

@Component
public class SlytherinTaskExecutor implements SlytherinTaskFactory {

    @Resource
    private TaskMapper taskMapper;

    @Resource
    private ScriptMapper scriptMapper;

    @Override
    public Boolean buildScriptAsync(BuildScriptParam buildScriptParam) {

        if (SourceEnum.getSourceEnum(buildScriptParam.getSourceCode())==null){
            return false;
        }
        TaskBO taskBO = taskMapper.selectById(buildScriptParam.getTaskId());
        Integer scriptId = taskBO.getScriptId();
        ScriptDO scriptDO = scriptMapper.selectById(scriptId);

        /**
         *  去查询 爬虫脚本
         */
        GroovyClassLoader classLoader = new GroovyClassLoader();

       // Class groovyClass = classLoader.parseClass(scriptDO.getScript());
       // Class groovyClass = new CategoryScript();
   //     try {
            String host = "123";
            Integer port = 80;
            HttpClientDownloader slytherinDownloader = new HttpClientDownloader();
            // HttpClientDownloader httpClientDownloader = new HttpClientDownloader();
            // 创建代理池并添加到下载器

//            SimpleProxyProvider proxyProvider = SimpleProxyProvider.from(new Proxy(host, port));
//            httpClientDownloader.setProxyProvider(proxyProvider);

            SlytherinScript groovyObject = new CategoryScript();;
            // 获取类名
//            String simpleName = groovyObject.getClass().getSimpleName();
//            //获取根路径
//            String path = System.getProperty("user.dir");

            Request seed = groovyObject.seed(buildScriptParam.getSeed());
            // 启动执行
            SlytherinSpider.create(groovyObject).setSite(Site.me()).thread(3).addRequest(seed).setDownloader(slytherinDownloader).run();
//        } catch (InstantiationException e) {
//            throw new RuntimeException(e);
//        } catch (IllegalAccessException e) {
//            throw new RuntimeException(e);
//        }
        return null;
    }
}
